package tech.dongliang.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import tech.dongliang.common.controller.CommonController;
import tech.dongliang.common.enums.EBizError;
import tech.dongliang.common.model.Tree;
import tech.dongliang.common.response.CommonResponse;
import tech.dongliang.common.response.ErrorData;
import tech.dongliang.system.model.SysDept;
import tech.dongliang.system.service.ISysDeptService;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xdzhang
 * @since 2019-01-18
 */
@Controller
@RequestMapping("/system/dept")
public class SysDeptController extends CommonController {
    private String prefix = "system/dept";
    @Autowired
    private ISysDeptService sysDeptService;

    @GetMapping()
    String dept() throws Exception {
        return prefix + "/list";
    }

    @ResponseBody
    @GetMapping("/list")
    public CommonResponse<List<SysDept>> list(@RequestParam(value = "deptName", required = false) String deptName) throws Exception {
        QueryWrapper query = new QueryWrapper();
        if (StringUtils.isNotBlank(deptName)) {
            query.eq("name", deptName);
        }
        List<SysDept> list = sysDeptService.list(query);
        return CommonResponse.success(list);
    }

    @GetMapping("/add/{pid}")
    public String add(@PathVariable("pid") Long pid, Model model) throws Exception {
        model.addAttribute("pid", pid);
        if (pid == 0) {
            model.addAttribute("pName", "总部门");
        } else {
            model.addAttribute("pName", sysDeptService.getById(pid).getName());
        }
        return prefix + "/add";
    }

    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, Model model) throws Exception {
        SysDept sysDept = sysDeptService.getById(deptId);
        model.addAttribute("sysDept", sysDept);
        if (0 == sysDept.getPid().intValue()) {
            model.addAttribute("parentDeptName", "总部门");
        } else {
            SysDept parDept = sysDeptService.getById(sysDept.getPid());
            model.addAttribute("parentDeptName", parDept.getName());
        }
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    public CommonResponse<Boolean> save(@Valid SysDept sysDept, BindingResult result) throws Exception {
        sysDept.setDelFlag(0);
        setPath(sysDept);
        if (sysDeptService.save(sysDept)) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

    private void setPath(SysDept sysDept) {
        if (sysDept.getPid().intValue() == 0) {
            sysDept.setPath("0:").setPid(0);
        } else {
            SysDept parent = sysDeptService.getById(sysDept.getPid());
            sysDept.setPath(parent.getPath() + parent.getId() + ":").setPid(parent.getId());
        }
    }

    /**
     * 修改
     */
    @ResponseBody
    @PostMapping("/update")
    public CommonResponse<Boolean> update(@Valid SysDept sysDept, BindingResult result) throws Exception {
        setPath(sysDept);
        if (sysDeptService.updateById(sysDept)) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public CommonResponse<Boolean> remove(Integer deptId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentId", deptId);
        if (sysDeptService.childCount(deptId) > 0) {
            return CommonResponse.error(new ErrorData(EBizError.DEPT_HAS_CHILD));
        }
        if (sysDeptService.getDeptUserNumber(deptId) > 0) {
            return CommonResponse.error(new ErrorData(EBizError.DEPT_HAS_USER));
        }
        if (sysDeptService.remove(deptId) > 0) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

    @GetMapping("/tree")
    @ResponseBody
    public CommonResponse<Tree<SysDept>> tree() throws Exception {
        Tree<SysDept> tree = sysDeptService.getTree();
        return CommonResponse.success(tree);
    }

    @GetMapping("/treeView")
    String treeView() throws Exception {
        return prefix + "/deptTree";
    }
}
